package com.oak.broke.config.mybatis.encript.encrypt;

import com.oak.broke.config.mybatis.encript.config.EncryptColumnInfo;
import com.oak.broke.config.mybatis.encript.config.Sm4SecretColumnConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class ProcessEncrypt {

    @Autowired(required = false)
    private List<ISm4SecretHandler> sm4EncryptSecretHandler;

    @Autowired
    private Sm4SecretColumnConfig sm4SecretColumnConfig;

    public Object processEncrypt(String column, Object value) {
        Object result = value;
        Map<String, EncryptColumnInfo> sm4SecretColumnConfigEncryptColumnInfoMap = sm4SecretColumnConfig.getEncryptColumnInfoMap();
        if (sm4SecretColumnConfigEncryptColumnInfoMap.containsKey(column)) {
            Class<?> clazz = sm4SecretColumnConfigEncryptColumnInfoMap.get(column).getJavaType();
            for (ISm4SecretHandler encryptHandle : sm4EncryptSecretHandler) {
                if (encryptHandle.support(clazz)) {
                    result = encryptHandle.encryptObject(value);
                    break;
                }
            }
        }
        return result;
    }

    public Object processDecrypt(String column, Object value) {
        Object result = value;
        Map<String, EncryptColumnInfo> sm4SecretColumnConfigEncryptColumnInfoMap = sm4SecretColumnConfig.getEncryptColumnInfoMap();
        if (sm4SecretColumnConfigEncryptColumnInfoMap.containsKey(column)) {
            Class<?> clazz = sm4SecretColumnConfigEncryptColumnInfoMap.get(column).getJavaType();
            for (ISm4SecretHandler encryptHandle : sm4EncryptSecretHandler) {
                if (encryptHandle.support(clazz)) {
                    result = encryptHandle.decryptObject(value);
                    break;
                }
            }
        }
        return result;
    }
}
